<template>
  <div class="category-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>商品分类管理</h2>
      <div class="header-actions">
        <button class="btn btn-primary" @click="showAddModal = true">
          <span class="icon">+</span>
          新增分类
        </button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-group">
          <label>分类名称</label>
          <input
            v-model="searchForm.categoryName"
            type="text"
            placeholder="请输入分类名称"
            class="form-control"
          />
        </div>

        <div class="form-group">
          <label>状态</label>
          <select v-model="searchForm.status" class="form-control">
            <option value="">全部状态</option>
            <option :value="1">启用</option>
            <option :value="0">停用</option>
          </select>
        </div>

        <div class="form-actions">
          <button class="btn btn-primary" @click="handleSearch">
            <span class="icon">🔍</span>
            搜索
          </button>
          <button class="btn btn-secondary" @click="handleReset">
            <span class="icon">🔄</span>
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>分类ID</th>
              <th>分类编码</th>
              <th>分类名称</th>
              <th>父分类</th>
              <th>层级</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in tableData" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ item.categoryCode || '-' }}</td>
              <td class="category-name">{{ item.categoryName }}</td>
              <td>{{ getParentCategoryName(item.parentId) }}</td>
              <td>{{ item.level || 1 }}</td>
              <td>
                <span :class="['status-badge', item.status === 1 ? 'active' : 'inactive']">
                  {{ item.status === 1 ? '启用' : '停用' }}
                </span>
              </td>
              <td>{{ formatDate(item.createdAt) }}</td>
              <td class="actions">
                <button class="btn btn-sm btn-info" @click="handleEdit(item)">
                  <span class="icon">✏️</span>
                  编辑
                </button>
                <button class="btn btn-sm btn-danger" @click="handleDelete(item)">
                  <span class="icon">🗑️</span>
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 空数据状态 -->
        <div v-if="tableData.length === 0" class="empty-state">
          <div class="empty-icon">📁</div>
          <p>暂无分类数据</p>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共 {{ total }} 条记录，当前第 {{ currentPage }} 页
      </div>
      <div class="pagination">
        <button
          class="btn btn-sm"
          :disabled="currentPage === 1"
          @click="handlePageChange(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
        <button
          class="btn btn-sm"
          :disabled="currentPage === totalPages"
          @click="handlePageChange(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除分类</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-body">
          <div class="delete-warning">
            <div class="warning-icon">⚠️</div>
            <div class="warning-content">
              <h4>确定要删除分类"{{ deletingItem?.categoryName }}"吗？</h4>
              <div class="product-warning">
                <p><strong>⚠️ 警告：</strong>删除分类将同时删除该分类下的所有商品！</p>
                <p>此操作不可逆，请谨慎操作。</p>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeDeleteModal">取消</button>
          <button class="btn btn-danger" @click="confirmDelete" :disabled="deleting">
            {{ deleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑分类' : '新增分类' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="handleSubmit">
            <div class="form-row">
              <div class="form-group">
                <label>分类名称 *</label>
                <input
                  v-model="formData.categoryName"
                  type="text"
                  required
                  class="form-control"
                  placeholder="请输入分类名称"
                />
              </div>
              <div class="form-group">
                <label>分类编码</label>
                <input
                  v-model="formData.categoryCode"
                  type="text"
                  class="form-control"
                  placeholder="请输入分类编码"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>父分类</label>
                <select v-model="formData.parentId" class="form-control">
                  <option value="">无父分类（顶级分类）</option>
                  <option v-for="category in categoryList" :key="category.id" :value="category.id">
                    {{ category.categoryName }}
                  </option>
                </select>
              </div>
              <div class="form-group">
                <label>层级</label>
                <input
                  v-model="formData.level"
                  type="number"
                  min="1"
                  class="form-control"
                  placeholder="请输入层级"
                />
              </div>
            </div>

            <div class="form-group">
              <label>状态</label>
              <select v-model="formData.status" class="form-control">
                <option :value="1">启用</option>
                <option :value="0">停用</option>
              </select>
            </div>

            <div class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">
                {{ showEditModal ? '更新' : '创建' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getCategoryPage, createCategory, updateCategory, deleteCategory, getCategoryList } from '@/api/commodity'

// 响应式数据
const tableData = ref([])
const categoryList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 弹窗状态
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const editingItem = ref(null)
const deletingItem = ref(null)
const deleting = ref(false)

// 搜索表单
const searchForm = reactive({
  categoryName: '',
  status: ''
})

// 表单数据
const formData = reactive({
  categoryName: '',
  categoryCode: '',
  parentId: '',
  level: 1,
  status: 1
})

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }

    const res = await getCategoryPage(params)
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const loadCategoryList = async () => {
  try {
    const res = await getCategoryList()
    categoryList.value = res.data || []
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    categoryName: '',
    status: ''
  })
  currentPage.value = 1
  loadData()
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadData()
}

const handleEdit = (item) => {
  editingItem.value = item
  Object.assign(formData, {
    categoryName: item.categoryName,
    categoryCode: item.categoryCode,
    parentId: item.parentId,
    level: item.level,
    status: item.status
  })
  showEditModal.value = true
}

const handleDelete = async (item) => {
  try {
    deletingItem.value = item

    // 直接显示删除确认对话框
    showDeleteModal.value = true
  } catch (error) {
    console.error('操作失败:', error)
    alert('操作失败，请稍后重试')
  }
}

const confirmDelete = async () => {
  if (!deletingItem.value) return

  deleting.value = true
  try {
    // 直接调用后端的删除接口，让后端处理所有逻辑
    await deleteCategory(deletingItem.value.id, true)

    alert('删除成功！')
    closeDeleteModal()
    loadData()
  } catch (error) {
    console.error('删除失败:', error)
    if (error.response && error.response.data && error.response.data.message) {
      alert('删除失败：' + error.response.data.message)
    } else {
      alert('删除失败，请稍后重试')
    }
  } finally {
    deleting.value = false
  }
}

const closeDeleteModal = () => {
  showDeleteModal.value = false
  deletingItem.value = null
  deleting.value = false
}

const handleSubmit = async () => {
  try {
    if (showEditModal.value) {
      await updateCategory(editingItem.value.id, formData)
      alert('更新成功')
    } else {
      await createCategory(formData)
      alert('创建成功')
    }
    closeModal()
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    alert('操作失败')
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingItem.value = null
  Object.assign(formData, {
    categoryName: '',
    categoryCode: '',
    parentId: '',
    level: 1,
    status: 1
  })
}

const getParentCategoryName = (parentId) => {
  if (!parentId) return '-'
  const category = categoryList.value.find(c => c.id === parentId)
  return category ? category.categoryName : '-'
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadData()
  loadCategoryList()
})
</script>

<style scoped>
.category-list {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:hover {
  background: #40a9ff;
}

.btn-secondary {
  background: #f0f0f0;
  color: #666;
}

.btn-secondary:hover {
  background: #e0e0e0;
}

.btn-info {
  background: #13c2c2;
  color: white;
}

.btn-danger {
  background: #ff4d4f;
  color: white;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

/* 搜索区域 */
.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-group label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.form-control {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-control:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
}

.form-actions {
  display: flex;
  gap: 8px;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.data-table th {
  background: #fafafa;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.data-table td {
  font-size: 14px;
  color: #666;
}

.category-name {
  font-weight: 500;
  color: #333;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-badge.inactive {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.actions {
  display: flex;
  gap: 4px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-info {
  color: #666;
  font-size: 14px;
}

/* 弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.modal-body .form-actions {
  justify-content: flex-end;
  margin-top: 20px;
}

/* 删除确认弹窗样式 */
.delete-modal {
  max-width: 500px;
}

.delete-warning {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 6px;
}

.warning-icon {
  font-size: 24px;
  color: #fa8c16;
  flex-shrink: 0;
}

.warning-content h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
}

.product-warning {
  color: #d4380d;
}

.product-warning p {
  margin: 8px 0;
  font-size: 14px;
}

.highlight {
  font-weight: bold;
  color: #d4380d;
  background: #fff2f0;
  padding: 2px 6px;
  border-radius: 3px;
}

.safe-delete {
  color: #52c41a;
}

.safe-delete p {
  margin: 8px 0;
  font-size: 14px;
}

.delete-options {
  margin-top: 20px;
  padding: 16px;
  background: #f6f6f6;
  border-radius: 6px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-label input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.btn-danger {
  background: #ff4d4f;
  color: white;
}

.btn-danger:hover {
  background: #ff7875;
}

.btn-danger:disabled {
  background: #ffccc7;
  cursor: not-allowed;
}

/* 响应式 */
@media (max-width: 768px) {
  .search-form {
    grid-template-columns: 1fr;
  }

  .form-row {
    grid-template-columns: 1fr;
  }

  .pagination-section {
    flex-direction: column;
    gap: 12px;
  }

  .actions {
    flex-direction: column;
  }
}
</style>


